<template>
  <div class="view">
    <div :id="id"></div>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, watch } from 'vue'
import loadScript from './loadScript.js'

// 定义组件属性
const props = defineProps({
  id: { type: String, default: '' },
  documentServerUrl: { type: String, default: '' },
  config: { type: Object, default: () => ({}) },
  document_fileType: { type: String, default: '' },
  document_title: { type: String, default: '' },
  documentType: { type: String, default: '' },
  editorConfig_lang: { type: String, default: '' },
  height: { type: String, default: '' },
  type: { type: String, default: '' },
  width: { type: String, default: '' },
  events_onAppReady: { type: Function, default: () => {} },
  events_onDocumentStateChange: { type: Function, default: () => {} },
  events_onMetaChange: { type: Function, default: () => {} },
  events_onDocumentReady: { type: Function, default: () => {} },
  events_onInfo: { type: Function, default: () => {} },
  events_onWarning: { type: Function, default: () => {} },
  events_onError: { type: Function, default: () => {} },
  events_onRequestSharingSettings: { type: Function, default: () => {} },
  events_onRequestRename: { type: Function, default: () => {} },
  events_onMakeActionLink: { type: Function, default: () => {} },
  events_onRequestInsertImage: { type: Function, default: () => {} },
  events_onRequestSaveAs: { type: Function, default: () => console.log('保存') },
  events_onRequestMailMergeRecipients: { type: Function, default: () => {} },
  events_onRequestCompareFile: { type: Function, default: () => {} },
  events_onRequestEditRights: { type: Function, default: () => {} },
  events_onRequestHistory: { type: Function, default: () => {} },
  events_onRequestHistoryClose: { type: Function, default: () => {} },
  events_onRequestHistoryData: { type: Function, default: () => {} },
  events_onRequestRestore: { type: Function, default: () => {} },
  events_onSave: { type: Function, default: () => console.log('保存') },
})

// 核心方法
const onLoad = () => {
  try {
    const id = props.id || ''
    if (!window.DocsAPI) throw new Error('DocsAPI is not defined')
    if (window?.DocEditor?.instances[id]) {
      console.log('Skip loading. Instance already exists', id)
      return
    }
    if (!window?.DocEditor?.instances) {
      window.DocEditor = { instances: {} }
    }

    const initConfig = {
      document: {
        fileType: props.document_fileType,
        title: props.document_title,
      },
      documentType: props.documentType,
      customSaveHandler: true,
      editorConfig: {
        lang: props.editorConfig_lang,
        customSaveHandler: true,
      },
      events: {
        onAppReady: onAppReady,
        onDocumentStateChange: props.events_onDocumentStateChange,
        onMetaChange: props.events_onMetaChange,
        onDocumentReady: props.events_onDocumentReady,
        onInfo: props.events_onInfo,
        onWarning: props.events_onWarning,
        onError: props.events_onError,
        onRequestSharingSettings: props.events_onRequestSharingSettings,
        onRequestRename: props.events_onRequestRename,
        onMakeActionLink: props.events_onMakeActionLink,
        onRequestInsertImage: props.events_onRequestInsertImage,
        onRequestSaveAs: props.events_onRequestSaveAs,
        onRequestMailMergeRecipients: props.events_onRequestMailMergeRecipients,
        onRequestCompareFile: props.events_onRequestCompareFile,
        onRequestEditRights: props.events_onRequestEditRights,
        onRequestHistory: props.events_onRequestHistory,
        onRequestHistoryClose: props.events_onRequestHistoryClose,
        onRequestHistoryData: props.events_onRequestHistoryData,
        onRequestRestore: props.events_onRequestRestore,
      },
      height: props.height,
      type: props.type,
      width: props.width,
      ...props.config,
    }

    const editor = window.DocsAPI.DocEditor(id, initConfig)
    window.DocEditor.instances[id] = editor
  } catch (err) {
    console.error(err)
    props.events_onError(err)
  }
}

const onAppReady = () => {
  const id = props.id || ''
  props.events_onAppReady(window.DocEditor.instances[id])
}

const onChangeProps = () => {
  const id = props.id || ''
  if (window?.DocEditor?.instances[id]) {
    window.DocEditor.instances[id].destroyEditor()
    window.DocEditor.instances[id] = undefined
    console.log('Important props have been changed. Load new Editor.')
    onLoad()
  }
}

// 监听属性变化
watch(() => props.config, onChangeProps, { deep: true })
watch(() => props.document_fileType, onChangeProps)
watch(() => props.document_title, onChangeProps)
watch(() => props.documentType, onChangeProps)
watch(() => props.editorConfig_lang, onChangeProps)
watch(() => props.height, onChangeProps)
watch(() => props.type, onChangeProps)
watch(() => props.width, onChangeProps)

// 生命周期钩子
onMounted(() => {
  console.log('props.documentServerUrl', props.documentServerUrl)

  let url = props.documentServerUrl
  if (!url.endsWith('/')) {
    url += '/'
  }
  const docApiUrl = `${url}web-apps/apps/api/documents/api.js`
  loadScript(docApiUrl, 'onlyoffice-api-script')
    .then(() => onLoad())
    .catch((err) => console.error(err))
})

onBeforeUnmount(() => {
  const id = props.id || ''
  if (window?.DocEditor?.instances[id]) {
    window.DocEditor.instances[id].destroyEditor()
    window.DocEditor.instances[id] = undefined
  }
})
</script>

<style lang="scss">
.view {
  width: 100%;
  height: 100%;

  iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
